package org.codefinger.dao;

import java.util.Map;

import org.codefinger.dao.impl.DataAccesser;
import org.codefinger.dao.impl.QueryParam;
import org.codefinger.dao.impl.SQLVisitor;
import org.codefinger.dao.impl.sql.UValue;

public class UpdateColumns implements Updater {

	private DataAccesser	dataAccesser;

	private String			table;

	private UValue			uValue;

	public UpdateColumns(DataAccesser dataAccesser, String table, String setValues) {
		super();
		this.dataAccesser = dataAccesser;
		this.table = table;
		this.uValue = dataAccesser.createUValue(setValues);
	}

	public UpdateWhere where(String condition) {
		return new UpdateWhere(dataAccesser, table, uValue, condition);
	}

	@Override
	public int execute(Object... params) {
		QueryParam queryParam = new QueryParam(params);
		SQLVisitor visitor = new SQLVisitor(queryParam);
		visitor.appendSQL("UPDATE ");
		visitor.appendSQL(table);
		uValue.visit(visitor);
		return dataAccesser.executeUpdate(visitor.getSQL(), visitor.getParams());
	}

	@Override
	public int execute(Map<String, Object> params) {
		QueryParam queryParam = new QueryParam(params);
		SQLVisitor visitor = new SQLVisitor(queryParam);
		visitor.appendSQL("UPDATE ");
		visitor.appendSQL(table);
		uValue.visit(visitor);
		return dataAccesser.executeUpdate(visitor.getSQL(), visitor.getParams());
	}

	@Override
	public UpdaterChain putParam(String name, Object value) {
		final QueryParam queryParam = new QueryParam();
		queryParam.setNamedParam(name, value);
		return new UpdaterChain() {

			@Override
			public UpdaterChain putParam(String name, Object value) {
				queryParam.setNamedParam(name, value);
				return this;
			}

			@Override
			public int execute() {
				SQLVisitor visitor = new SQLVisitor(queryParam);
				visitor.appendSQL("UPDATE ");
				visitor.appendSQL(table);
				uValue.visit(visitor);
				return dataAccesser.executeUpdate(visitor.getSQL(), visitor.getParams());
			}

		};
	}

}
